package com.weds.frame.domain.typeHandler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.HashSet;
import java.util.Set;

@MappedJdbcTypes(JdbcType.ARRAY)
@MappedTypes(Set.class)
public class SetTypeHandler extends BaseTypeHandler<Set> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter);
    }

    @Override
    public Set getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getArray(resultSet.getArray(s));
    }

    @Override
    public Set getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getArray(resultSet.getArray(i));
    }

    @Override
    public Set getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getArray(callableStatement.getArray(i));
    }

    private Set getArray(Array array) {
        if (array == null) {
            return null;
        }
        try {
            return JSONObject.parseObject(JSON.toJSONString(array.getArray()), HashSet.class);
        } catch (Exception e) {
        }
        return null;
    }

}